﻿using System;
using System.IO;
using System.Linq;
using System.Reflection;
using T2V.SharePoint.Report.DocXGenerator;
using T2V.SharePoint.Report.Excel;

namespace T2V.SharePoint.Report
{
    public class ExcelGenericReport<T>  where T : IReportBase
    {
        public T ReportData { get; set; }
        public string Template { get; set; }

        public ExcelGenericReport(T data, string template)
        {
            ReportData = data;
            Template = template;
        }

        public byte[] GetReportData()
        {
            FileInfo existingFile = new FileInfo(Template);
            MemoryStream ms = new MemoryStream();
            FileStream fs = File.Open(Template, FileMode.Open);
            //FileStream ss = File.Create("c:\\test.xlsx");

            using (ExcelPackage package = new ExcelPackage(ms, fs))
            {
                ExcelWorksheet worksheet = package.Workbook.Worksheets[1];

                FillSingleValue(worksheet, ReportData);
            }
            fs.Close();
            //ss.Close();
            ms.Flush();
            return ms.GetBuffer();
            return null;
        }

        private void FillSingleValue(ExcelWorksheet worksheet, T ReportData)
        {
            Type type = typeof(T);
            string results = string.Empty;

            foreach (PropertyInfo item in type.GetProperties(BindingFlags.Public | BindingFlags.Instance))
            {
                var cell = item.GetCustomAttributes(typeof(CellAttribute), true).Cast<CellAttribute>().FirstOrDefault();
                if (cell != null && !string.IsNullOrEmpty(cell.Index))
                {
                    var rawdata = item.GetValue(ReportData, null);
                    if (rawdata != null)
                    {
                        worksheet.Cells[cell.Index].Value = rawdata.ToString();
                        
                    }

                }
            }
            
        }
        public void Save(string filename)
        {
            File.WriteAllBytes(filename, GetReportData());
        }
    }
}
